local skynet = require "skynet"
local cluster = require "cluster"
local sharedata = require "sharedata"
require "skynet.manager"

local PROXY = {}

local dataser = nil


function PROXY.SyncData()
    skynet.fork(function()
        while true do          
            local ok, ret = pcall(PROXY.GetData)
            if ok then                       
                skynet.error("[proxyser] SyncData syncdata succ")
                sharedata.update("GameServerShareObj", ret)
                break
            else
                 skynet.error("[proxyser] SyncData syncdata fail")
            end
           
            skynet.sleep(300)    
        end
    end)
end

function PROXY.GetData() 

    local GameServer
    if dataser then            
        GameServer = cluster.call("master", dataser,"get_gameServerObj") 
    else
        dataser  = cluster.query("master", "centerser")
        GameServer = cluster.call("master", dataser,"get_gameServerObj") 
    end        
    return GameServer
    
end

function PROXY.UpdateGameServer(GameServer)
    
    skynet.error("[proxyser] UpdateGameServer...")
    sharedata.update("GameServerShareObj", GameServer)

end


function PROXY.start(...)
  
    skynet.error("proxyser start...")
    sharedata.new("GameServerShareObj", GameServer) 
     
    PROXY.SyncData()
    
end

skynet.start(function()
	skynet.dispatch("lua", function(_,_, command, ...)
		local f = PROXY[command]
		skynet.ret(skynet.pack(f(...)))
	end)
    math.randomseed(os.time())
end)